package cn.com.infcn.monitor.task.jvm.impl;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

import javax.management.MBeanServerConnection;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.infcn.monitor.bean.IFCResponseBean;
import cn.com.infcn.monitor.jvm.bean.IFCJVMRuntime;
import cn.com.infcn.monitor.task.impl.BaseTask;
import cn.com.infcn.monitor.util.IFCBeanUtils;
import cn.com.infcn.monitor.util.IFCMinitorConstanst;

/**
 * Java 虚拟机的运行时系统的管理接口。
 * @author jijs
 *
 */
public class JVMRuntimeTask extends BaseTask {

	private final static Logger logger = LoggerFactory.getLogger(JVMRuntimeTask.class);

	public JVMRuntimeTask(IoSession session, Object message) {
		super(session, message);
	}

	@Override
	public void execute() throws Exception {
		IFCResponseBean result = jvmRuntime();
		sendResponse(result);
	}

	public IFCResponseBean jvmRuntime() {
		IFCResponseBean result = new IFCResponseBean();
		MBeanServerConnection mbs = null;
		try {
			// 获取MBeanServerConnection
			mbs = MBeanServerConnectionFactory.getInstance(IFCMinitorConstanst.JMXURL);
		} catch (IOException e) {
			logger.error("jmx.url 连接异常！" + e.getMessage());
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_ERROR);
			result.setResponseMsg("jmx.url 连接异常！");
			return result;
		}

		try {
			RuntimeMXBean runtimeMXBean = ManagementFactory.newPlatformMXBeanProxy(mbs,
					ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);

			IFCJVMRuntime ifcRuntime = new IFCJVMRuntime();

			IFCBeanUtils.copyProperties(runtimeMXBean, ifcRuntime);

			result.setResult(ifcRuntime);
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_OK);
		} catch (Exception e) {
			logger.error(e.getMessage());
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_ERROR);
			result.setResponseMsg(e.getMessage());
		}

		return result;
	}

	public static void main(String[] args) {
		JVMRuntimeTask task = new JVMRuntimeTask(null, null);
		task.jvmRuntime();
	}
}
